const api = require('../../../ws_micro_shop/utils/api.js');
const app = getApp();
Page({
  data: {
    showGoodsType: false,
    typeInfo: '',
    showHotSales: false,
    showShareSetting: false,
    shareMoneyType: 0,
    value: [0, 0],
    level_1_type: [],
    level_2_type: [],
    cat_id: 0,
    goodsAvatar: [],
    goodsPicList: [],
    serviceTxt: '',
    serDisabled: false,
    currTemp: '',
    tempId: 0,
    currCard: '',
    addCard: [],
    goods_card: [],
    isSpecsUsed: false,
    isDetailShow: false,
    itemList: [],
    item: {
      num: 0,
      price: 0,
      itemNumber: '',
      low_num: 1,
      top_num: 0,
      wechat_discount: 10,
      discount_price: 0,
      begin_time: '',
      end_time: '',
      checked: false,
      pic: '',
    },
    imgUrl: app.imgUrl,
    integral_list: [
      {
        id: 'intergral',
        name: '分'
      },
      {
        id: 'percent',
        name: '%'
      }
    ],
    integral_forehead_list: [
      {
        id: 'cash',
        name: '￥'
      },
      {
        id: 'percent',
        name: '%'
      }
    ],
    integral_list_name: '分',
    integral_list_selected: 'intergral',
    integral_forehead_list_name: '￥',
    integral_forehead_list_selected: 'cash',
  },
  onLoad(options) {
    let that = this;
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    this.loadData();
  },
  onShow() {
    let usetype = wx.getStorageSync('usetype');
    let resData = wx.getStorageSync('resPic');
    let imgUrl;
    if (resData) {
      imgUrl = JSON.parse(resData).url;
    }
    if (usetype === 'avatar') {
      let avatar = this.data.goodsAvatar;
      avatar.push(imgUrl);
      this.setData({
        goodsAvatar: avatar,
      });
    } else if (usetype === 'goodspic') {
      let pics = this.data.goodsPicList;
      pics.push(imgUrl);
      this.setData({
        goodsPicList: pics,
      });
    } else if (usetype === 'specspic') {
      let specsListItem = this.data.specsListItem;
      specsListItem.pic = imgUrl;
      let specsIndex = this.data.specsIndex;
      this.setData({
        specsListItem: specsListItem,
        [`specsList[${specsIndex}]`]: specsListItem,
      })
    }
  },
  onHide() {
    wx.removeStorageSync('resPic');
    wx.removeStorageSync('usetype');
  },
  onUnload() {
    wx.removeStorageSync('resPic');
    wx.removeStorageSync('usetype');
  },
  pickintergrallist(e) {
    let index = Number(e.detail.value);
    let { integral_list } = this.data;
    this.setData({
      integral_list_name: integral_list[index].name,
      integral_list_selected: integral_list[index].id,
    })
  },
  pickintergralforeheadlist(e) {
    let index = Number(e.detail.value);
    let { integral_forehead_list } = this.data;
    this.setData({
      integral_forehead_list_name: integral_forehead_list[index].name,
      integral_forehead_list_selected: integral_forehead_list[index].id,
    })
  },
  loadData() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.adminer.goodsEdit,
      method: 'GET',
      success: function (res) {
        if (res.code === 0) {
          let catlist = res.data.cat_list;
          let cardList = res.data.card_list;
          let freight = res.data.postageRiles;
          that.setData({
            level_1_type: catlist,
            level_2_type: catlist[0].child,
            cardList,
            freight,
          });
        }
      },
    });
  },
  specsUsed() {
    this.setData({
      isSpecsUsed: !this.data.isSpecsUsed,
    });
  },
  detailShow() {
    this.setData({
      isDetailShow: !this.data.isDetailShow,
    });
  },
  bindSpecs(e) {
    let index = e.currentTarget.dataset.index;
    let value = e.detail.value;
    console.info('----------index-------', index)
    let specsListItem = this.data.specsListItem;
    for (var key in specsListItem) {
      if (key === index) {
        specsListItem[key] = value;
      }
    }
    let specsIndex = this.data.specsIndex;
    this.setData({
      specsListItem: specsListItem,
      [`specsList[${specsIndex}]`]: specsListItem,
    })
    console.info('-----------------specsList------------', this.data.specsList)
    console.info('-----------------specsListItem------------', this.data.specsListItem)
  },
  bindTimeChange: function (e) {
    let index = e.currentTarget.dataset.index;
    let specsListItem = this.data.specsListItem;
    if (index === 'begin_time') {
      specsListItem.begin_time = e.detail.value;
    } else {
      specsListItem.end_time = e.detail.value;
    }
    let specsIndex = this.data.specsIndex;
    this.setData({
      specsListItem: specsListItem,
      [`specsList[${specsIndex}]`]: specsListItem,
    })
    console.info('-----------------specsList------------', this.data.specsList)
    console.info('-----------------specsListItem------------', this.data.specsListItem)
  },
  endTimeChange: function (e) {
    this.setData({

    })
  },
  bindSpecsGroup(e) {
    this.setData({
      specsGroup: e.detail.value,
    })
  },
  addSpecsGroup(e) {
    if (!this.data.specsGroup) {
      wx.showToast({
        title: '规格组不能为空',
        icon: 'none',
      });
      return;
    }
    for (let i = 0; i < this.data.itemList.length; i++) {
      if (this.data.itemList[i].list && this.data.itemList[i].list.length === 0) {
        wx.showToast({
          title: '规格值不能为空',
          icon: 'none',
        });
        this.setData({
          specsGroup: '',
        })
        return;
      }
    }
    let item = [{
      name: this.data.specsGroup,
      list: [],
      value: '',
    }]
    this.setData({
      itemList: this.data.itemList.concat(item),
      specsGroup: '',
    })
  },
  deleteSpecGroup(e) {
    let index = e.currentTarget.dataset.index;
    let itemList = this.data.itemList;
    itemList.splice(index, 1);
    this.setData({
      itemList: itemList,
      specsList: this.serialArray(itemList) || [],
    })
     
    console.info('-----------------itemList------------', this.data.itemList)
    console.info('-----------------specsList------------', this.data.specsList)
  },
  bindSpecsValue(e) {
    this.setData({
      specsValue: e.detail.value,
    })
  },
  addSpecsValue(e) {
    if (!this.data.specsValue) {
      wx.showToast({
        title: '规格值不能为空',
        icon: 'none',
      });
      return;
    }
    let item = [{
      name: this.data.specsValue,
    }]
    let index = e.currentTarget.dataset.index;
    let list = this.data.itemList[index].list;
    list = list.concat(item);
    this.setData({
      [`itemList[${index}].list`]: list,
      [`itemList[${index}].value`]: '',
      specsValue: '',
    })
    this.setData({
      specsList: this.serialArray(this.data.itemList) || [],
    })
    console.info('-----------------specsList------------', this.data.specsList)
  },
  deleteSpecValue(e) {
    let index = e.currentTarget.dataset.index;
    let idx = e.currentTarget.dataset.idx;
    let itemList = this.data.itemList;
    itemList[index].list.splice(idx, 1);
    console.info('-----------------itemList------------', itemList)
    this.setData({
      itemList: itemList,
      specsList: this.serialArray(itemList) || [],
    })
    console.info('-----------------specsList------------', this.data.specsList)
  },
  serialArray(arr){
    var lengthArr = [];
    var productArr = [];
    var result = [];
    var length = 1;
    for(var i = 0; i<arr.length; i++){
      var len = arr[i].list.length;
      if (len > 0) {
        lengthArr.push(len);
        var product = i === 0 ? 1 : arr[i - 1].list.length * productArr[i - 1];
        productArr.push(product);
        length *= len;
      }
    }
    for (var i = 0; i < length; i++) {
      var resultItem = '';
      var list = [];
      for (var j = 0; j < arr.length; j++) {
        if (arr[j].list && arr[j].list.length > 0) {
          let name = arr[j].list[Math.floor(i / productArr[j]) % lengthArr[j]].name;
          let group_name = arr[j].name;
          resultItem = resultItem ? resultItem + '-' + name : name;
          list = list.concat([{
            attr_name: name,
            attr_group_name: group_name
          }])
        }
      }
      result.push({
        name:resultItem,
        attr_list: list
      });
    }
    result.forEach((one, index) => {
      one = Object.assign(one, this.data.item)
      if (index === 0) {
        one.checked = true;
      }
    })
    this.setData({
      specsListItem: arr.length === 0 ? [] : result[0],
      specsIndex: 0,
    })
    return arr.length === 0 ? [] : result
  },
  chooseCateType(e) {
    let idx = e.currentTarget.dataset.index;
    this.data.specsList.forEach((item, index) => {
      item.checked = false;
      if (idx === index) {
        item.checked = true;
      }
    })
    this.setData({
      specsList: this.data.specsList,
      specsListItem: this.data.specsList[idx],
      specsIndex: idx,
    })
  },
  showGoodsTypeModal() {
    this.setData({
      showGoodsType: true,
    });
  },
  typePickerConfirm(e) {
    let value = this.data.value;
    let level1name = this.data.level_1_type[value[0]].name;
    let level2name;
    let typeInfo;
    let cat_id;
    if (this.data.level_2_type[value[1]]) {
      level2name = this.data.level_2_type[value[1]].name;
      cat_id = this.data.level_2_type[value[1]].id;
      typeInfo = level1name + '->' + level2name;
    } else {
      cat_id = this.data.level_1_type[value[0]].id;
      typeInfo = level1name;
    }
    this.setData({
      typeInfo,
      cat_id,
      showGoodsType: false,
    });
  },
  hideTypePicker() {
    this.setData({
      showGoodsType: false,
    });
  },
  typePickerChange(e) {
    let value = e.detail.value;
    let level_one = this.data.level_1_type;
    let level1 = value[0];
    let level2 = value[1];
    if (this.data.value[0] !== level1) {
      this.setData({
        value: [level1, 0],
        level_2_type: level_one[level1].child,
      });
    } else {
      this.setData({
        value: [level1, level2],
      });
    }
  },
  pickGoodsAvatar() {
    let list = this.data.goodsAvatar;
    let len = list.length;
    if (len < 1) {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          let src = res.tempFilePaths[0];
          let sceneName = 'square';
          let usetype = 'avatar';
          let url = 'utility/file/upload';
          if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
            url = app.util.url(url, { type: 'image', thumb: '0' });
          }
          wx.setStorage({
            key: 'uploadUrl',
            data: url,
          });
          wx.navigateTo({
            url: `/common/component/cropper/cropper?sceneName=${sceneName}&src=${src}&usetype=${usetype}`,
          });
        },
      });
    } else {
      wx.showToast({
        title: '只能上传1张商品缩略图',
        icon: 'none',
      });
    }
  },
  clearAvatar() {
    this.setData({
      goodsAvatar: [],
    });
  },
  pickSpecsAvatar() {
    let list = this.data.specsListItem;
    if (list && list.pic === '') {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          let src = res.tempFilePaths[0];
          let sceneName = 'square';
          let usetype = 'specspic';
          let url = 'utility/file/upload';
          if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
            url = app.util.url(url, { type: 'image', thumb: '0' });
          }
          wx.setStorage({
            key: 'uploadUrl',
            data: url,
          });
          wx.navigateTo({
            url: `/common/component/cropper/cropper?sceneName=${sceneName}&src=${src}&usetype=${usetype}`,
          });
        },
      });
    } else {
      wx.showToast({
        title: '只能上传1张商品规格图片',
        icon: 'none',
      });
    }
  },
  clearSpecsAvatar() {
    let specsListItem = this.data.specsListItem;
    specsListItem.pic = '';
    let specsIndex = this.data.specsIndex;
    this.setData({
      specsListItem: specsListItem,
      [`specsList[${specsIndex}]`]: specsListItem,
    })
  },
  pickGoodsPics() {
    let list = this.data.goodsPicList;
    let len = list.length;
    if (len < 6) {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          let src = res.tempFilePaths[0];
          let sceneName = 'square';
          let usetype = 'goodspic';
          let url = 'utility/file/upload';
          if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
            url = app.util.url(url, { type: 'image', thumb: '0' });
          }
          wx.setStorage({
            key: 'uploadUrl',
            data: url,
          });
          wx.navigateTo({
            url: `/common/component/cropper/cropper?sceneName=${sceneName}&src=${src}&usetype=${usetype}`,
          });
        },
      });
    } else {
      wx.showToast({
        title: '最多只能上传6张商品图片',
        icon: 'none',
      });
    }
  },
  delPicItem(e) {
    let index = e.currentTarget.dataset.idx;
    let piclist = this.data.goodsPicList;
    piclist.splice(index, 1);
    this.setData({
      goodsPicList: piclist,
    });
  },
  openConfSer(e) {
    if (e.detail.value.length > 0) {
      this.setData({
        serviceTxt: '',
        serDisabled: true,
      });
    } else {
      this.setData({
        serDisabled: false,
      });
    }
  },
  bindFeightChange(e) {
    let feightIdx = e.detail.value;
    let temp = this.data.freight[feightIdx].name;
    let tempId = this.data.freight[feightIdx].id;
    this.setData({
      currTemp: temp,
      tempId,
    });
  },
  quickBuyChange(e) {
    let val = Number(e.detail.value);
    if (val === 1) {
      this.setData({
        showHotSales: true,
      });
    } else if (val === 0) {
      this.setData({
        showHotSales: false,
      });
    } else {
      this.setData({
        showHotSales: false,
      });
    }
  },
  shareChange(e) {
    let val = Number(e.detail.value);
    if (val === 1) {
      this.setData({
        showShareSetting: true,
      });
    } else if (val === 0) {
      this.setData({
        showShareSetting: false,
      });
    } else {
      this.setData({
        showShareSetting: false,
      });
    }
  },
  bindCardListChange(e) {
    let cardIdx = e.detail.value;
    let card = this.data.cardList[cardIdx].name;
    let cardId = this.data.cardList[cardIdx].id;
    this.setData({
      currCard: card,
      currCardId: cardId,
    });
  },
  sendCard() {
    let cards = this.data.addCard;
    let goods_card = this.data.goods_card;
    let card = this.data.currCard;
    let cardid = this.data.currCardId;
    if (cards.length < 10) {
      if (card && cardid) {
        cards.push(card);
        goods_card.push(cardid);
      }
    } else {
      wx.showToast({
        title: '最多只能添加10张卡券',
        icon: 'none',
      });
    }
    this.setData({
      addCard: cards,
      goods_card,
    });
  },
  cardRemove(e) {
    let index = e.currentTarget.dataset.idx;
    let cards = this.data.addCard;
    let goods_card = this.data.goods_card;
    cards.splice(index, 1);
    goods_card.splice(index, 1);
    this.setData({
      addCard: cards,
      goods_card,
    });
  },
  shareMoneyTypeChange(e) {
    let val = Number(e.detail.value);
    if (val === 1) {
      this.setData({
        shareMoneyType: 1,
      });
    } else if (val === 0) {
      this.setData({
        shareMoneyType: 0,
      });
    } else {
      this.setData({
        shareMoneyType: 0,
      });
    }
  },
  releaseGoods(e) {
    let model = {};
    let full_cut = {};
    let integral = {};
    let formdata = e.detail.value;
    let cat_id = this.data.cat_id;
    if (!cat_id) {
      wx.showToast({
        title: '商品分类不能为空',
        icon: 'none',
      });
      return;
    }
    if (!formdata.name) {
      wx.showToast({
        title: '商品名称不能为空',
        icon: 'none',
      });
      return;
    }
    if (!formdata.cover_pic) {
      wx.showToast({
        title: '商品缩略图不能为空',
        icon: 'none',
      });
      return;
    }
    if (!formdata.goods_pic_list) {
      wx.showToast({
        title: '商品图片不能为空',
        icon: 'none',
      });
      return;
    }
    if (!formdata.price) {
      wx.showToast({
        title: '售价不能为空',
        icon: 'none',
      });
      return;
    }
    if (formdata.price < 0.01) {
      wx.showToast({
        title: '售价不能低于' + this.data.unit + '0.01',
        icon: 'none',
      });
      return;
    }
    if (formdata.price > 99999999) {
      wx.showToast({
        title: '售价超过限制',
        icon: 'none',
      });
      return;
    }
    if (!this.data.isSpecsUsed) {
      if (!formdata.goods_num) {
        wx.showToast({
          title: '商品库存不能为空',
          icon: 'none',
        });
        return;
      }
      if (formdata.goods_num < 0) {
        wx.showToast({
          title: '商品库存不能为负数',
          icon: 'none',
        });
        return;
      }
      if (formdata.limit_count > 0 && formdata.min_num > formdata.limit_count) {
        wx.showToast({
          title: '商品起购数量不能大于限购数量',
          icon: 'none',
        });
        return;
      }
    }
    if (!formdata.original_price) {
      wx.showToast({
        title: '原价不能为空',
        icon: 'none',
      });
      return;
    }
    if (formdata.original_price < 0.01) {
      wx.showToast({
        title: '原价不能低于' + this.data.unit + '0.01',
        icon: 'none',
      });
      return;
    }
    if (formdata.original_price > 99999999) {
      wx.showToast({
        title: '原价超过限制',
        icon: 'none',
      });
      return;
    }
    if (!formdata.totalcnf) {
      wx.showToast({
        title: '请选择库存减少方式',
        icon: 'none',
      });
      return;
    }
    if (!formdata.stock_alarm) {
      wx.showToast({
        title: '库存预警不能为空',
        icon: 'none',
      });
      return;
    }
    if (formdata.stock_alarm < 0) {
      wx.showToast({
        title: '库存预警不能为负数',
        icon: 'none',
      });
      return;
    }
    if (!formdata.individual_share) {
      wx.showToast({
        title: '请选择是否开启单独分销',
        icon: 'none',
      });
      return;
    }
    if (Number(formdata.individual_share) === 1) {
      if (!formdata.share_commission_first || !formdata.share_commission_second || !formdata.share_commission_third) {
        wx.showToast({
          title: '分销佣金不能为空',
          icon: 'none',
        });
        return;
      }
    }
    if (!formdata.detail) {
      wx.showToast({
        title: '商品详情不能为空',
        icon: 'none',
      });
      return;
    }
    formdata.use_attr = this.data.isSpecsUsed ? 1 : 0;
    formdata.show_attr = this.data.isDetailShow ? (this.data.isSpecsUsed ? 1 : 0) : 0;
    model = JSON.parse(JSON.stringify(formdata));
    delete model.full_cut_pieces;
    delete model.full_cut_forehead;
    delete model.integral_give;
    delete model.integral_forehead;
    delete model.integral_more;
    model.cat_id = this.data.cat_id;
    model.freight = this.data.tempId;
    full_cut = {
      pieces: formdata.full_cut_pieces,
      forehead: formdata.full_cut_forehead,
    };
    integral = {
      give: formdata.integral_give + (this.data.integral_list_selected === 'percent' && formdata.integral_give > 0 ? '%' : ''),
      forehead: formdata.integral_forehead + (this.data.integral_forehead_list_selected === 'percent' && formdata.integral_forehead > 0 ? '%' : ''),
      more: formdata.integral_more,
    };
    wx.showLoading({
      title: '正在发布...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.adminer.goodsEdit,
      method: 'POST',
      data: {
        goods_card: JSON.stringify(this.data.goods_card),
        model: JSON.stringify(model),
        full_cut: JSON.stringify(full_cut),
        integral: JSON.stringify(integral),
        attr_group_list: JSON.stringify(this.data.itemList || []),
        attr_group_list2: JSON.stringify(this.data.specsList || []),
      },
      success: function (resp) {
        wx.hideLoading();
        if (resp.code === 0) {
          if (Number(model.status) === 1) {
            wx.redirectTo({
              url: '/ws_micro_shop_seller/pages/goods-manage/index?status=1&type=0',
            });
          } else {
            wx.redirectTo({
              url: '/ws_micro_shop_seller/pages/goods-manage/index?status=0&type=0',
            });
          }
        } else {
          wx.showToast({
            title: resp.msg,
            icon: 'none',
            duration: 3000,
          });
        }
      },
    });
  },
  uploadimg(arg) {
    let that = this;
    wx.chooseImage({
      count: arg.max - that.data[arg.arrname].length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 10000,
        });
        let uploadImgCount = 0;
        for (let i = 0, h = tempFilePaths.length; i < h; i++) {
          wx.uploadFile({
            url: arg.url,
            filePath: tempFilePaths[i],
            name: 'image',
            formData: { _acid: app.siteInfo.acid },
            header: {
              'Content-Type': 'multipart/form-data',
            },
            success: function (res) {
              uploadImgCount++;
              let resp = JSON.parse(res.data);
              let productInfo = that.data[arg.arrname];
              productInfo.push(resp.data.url);
              that.setData({
                [arg.arrname]: productInfo,
              });
              if (uploadImgCount === tempFilePaths.length) {
                wx.hideToast();
              }
            },
            fail: function (res) {
              wx.hideToast();
              wx.showModal({
                title: '错误提示',
                content: '上传图片失败',
                showCancel: false,
              });
            },
          });
        }
      },
    });
  },
});
